'use client'

import { useEffect, useRef } from 'react'
import * as d3 from 'd3'

interface CandlestickData {
  time: string
  open: number
  high: number
  low: number
  close: number
  volume: number
}

interface CandlestickChartProps {
  data: CandlestickData[]
  width?: number
  height?: number
}

export function CandlestickChart({ data, width = 800, height = 400 }: CandlestickChartProps) {
  const svgRef = useRef<SVGSVGElement>(null)

  useEffect(() => {
    if (!data || data.length === 0) return

    const svg = d3.select(svgRef.current)
    svg.selectAll("*").remove()

    const margin = { top: 20, right: 30, bottom: 40, left: 60 }
    const chartWidth = width - margin.left - margin.right
    const chartHeight = height - margin.top - margin.bottom

    const g = svg.append("g")
      .attr("transform", `translate(${margin.left},${margin.top})`)

    // Scales
    const xScale = d3.scaleBand()
      .domain(data.map(d => d.time))
      .range([0, chartWidth])
      .padding(0.1)

    const yScale = d3.scaleLinear()
      .domain([
        d3.min(data, d => Math.min(d.low, d.close)) * 0.98,
        d3.max(data, d => Math.max(d.high, d.close)) * 1.02
      ])
      .range([chartHeight, 0])

    // Axes
    g.append("g")
      .attr("transform", `translate(0,${chartHeight})`)
      .call(d3.axisBottom(xScale))
      .selectAll("text")
      .style("text-anchor", "end")
      .attr("dx", "-.8em")
      .attr("dy", ".15em")
      .attr("transform", "rotate(-45)")

    g.append("g")
      .call(d3.axisLeft(yScale))

    // Candlesticks
    const candlesticks = g.selectAll(".candlestick")
      .data(data)
      .enter()
      .append("g")
      .attr("class", "candlestick")

    // Candle body
    candlesticks.append("rect")
      .attr("x", d => xScale(d.time)!)
      .attr("y", d => yScale(Math.max(d.open, d.close)))
      .attr("width", xScale.bandwidth())
      .attr("height", d => Math.abs(yScale(d.open) - yScale(d.close)))
      .attr("fill", d => d.close > d.open ? "#10b981" : "#ef4444")

    // Candle wicks
    candlesticks.append("line")
      .attr("x1", d => xScale(d.time)! + xScale.bandwidth() / 2)
      .attr("x2", d => xScale(d.time)! + xScale.bandwidth() / 2)
      .attr("y1", d => yScale(d.high))
      .attr("y2", d => yScale(d.low))
      .attr("stroke", d => d.close > d.open ? "#10b981" : "#ef4444")
      .attr("stroke-width", 1)

  }, [data, width, height])

  return (
    <svg 
      ref={svgRef} 
      width={width} 
      height={height}
      className="w-full h-full"
    />
  )
}
